"""
配置管理API路由
提供品牌、商品名称、单位、营销词和系统配置的CRUD操作
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query, Path
from sqlalchemy.orm import Session
from typing import List, Optional, Dict, Any
import logging

from backend.database.database import get_db
from backend.routes.auth import get_current_active_user, User
from backend.data_clean.models import (
    BrandConfig, CommonProductName, UnitConfig, 
    MarketingWordConfig, SystemConfig, UnitConversion
)
from backend.data_clean.schemas import (
    BrandConfig as BrandConfigSchema,
    BrandConfigCreate, BrandConfigUpdate,
    CommonProductName as CommonProductNameSchema,
    CommonProductNameCreate, CommonProductNameUpdate,
    UnitConfig as UnitConfigSchema,
    UnitConfigCreate, UnitConfigUpdate,
    MarketingWordConfig as MarketingWordConfigSchema,
    MarketingWordConfigCreate, MarketingWordConfigUpdate,
    SystemConfig as SystemConfigSchema,
    SystemConfigCreate, SystemConfigUpdate,
    BulkCreateRequest, BulkStatusUpdate
)
from backend.data_clean.config_manager import config_manager

# 创建路由
router = APIRouter(
    prefix="/api/config",
    tags=["配置管理"],
    responses={404: {"description": "Not found"}},
)

# 设置日志
logger = logging.getLogger(__name__)

# 品牌配置API

@router.get("/brand-config", response_model=Dict[str, Any])
async def get_brands(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"), 
    category: Optional[str] = None,
    is_active: Optional[bool] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取品牌列表"""
    query = db.query(BrandConfig)
    
    if category:
        query = query.filter(BrandConfig.category == category)
    
    if is_active is not None:
        query = query.filter(BrandConfig.is_active == is_active)
    
    # 获取总数
    total = query.count()
    
    # 计算分页
    skip = (page - 1) * page_size
    
    # 获取分页数据
    brands = query.order_by(BrandConfig.id).offset(skip).limit(page_size).all()
    
    return {
        "items": brands,
        "total": total
    }

@router.post("/brand-config", response_model=BrandConfigSchema)
async def create_brand(
    brand: BrandConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建品牌"""
    # 检查是否已存在
    existing_brand = db.query(BrandConfig).filter(BrandConfig.name == brand.name).first()
    if existing_brand:
        raise HTTPException(status_code=400, detail="品牌名称已存在")
    
    new_brand = BrandConfig(**brand.dict())
    db.add(new_brand)
    db.commit()
    db.refresh(new_brand)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_brand

@router.put("/brand-config/{brand_id}", response_model=BrandConfigSchema)
async def update_brand(
    brand_id: int,
    brand: BrandConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新品牌"""
    db_brand = db.query(BrandConfig).filter(BrandConfig.id == brand_id).first()
    if not db_brand:
        raise HTTPException(status_code=404, detail="品牌不存在")
    
    # 如果更新名称，检查新名称是否已存在
    if brand.name and brand.name != db_brand.name:
        existing = db.query(BrandConfig).filter(BrandConfig.name == brand.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="品牌名称已存在")
    
    # 更新字段
    for key, value in brand.dict(exclude_unset=True).items():
        setattr(db_brand, key, value)
    
    db.commit()
    db.refresh(db_brand)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_brand

@router.delete("/brand-config/{brand_id}")
async def delete_brand(
    brand_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除品牌"""
    db_brand = db.query(BrandConfig).filter(BrandConfig.id == brand_id).first()
    if not db_brand:
        raise HTTPException(status_code=404, detail="品牌不存在")
    
    db.delete(db_brand)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "品牌已删除"}

@router.post("/brand-config/bulk", response_model=Dict[str, Any])
async def bulk_create_brands(
    request: BulkCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建品牌"""
    created = []
    errors = []
    
    for item in request.items:
        try:
            # 验证必填字段
            if "name" not in item:
                errors.append({"item": item, "error": "缺少必填字段name"})
                continue
            
            # 检查是否已存在
            existing = db.query(BrandConfig).filter(BrandConfig.name == item["name"]).first()
            if existing:
                errors.append({"item": item, "error": "品牌名称已存在"})
                continue
            
            # 创建新品牌
            category = item.get("category")
            is_active = item.get("is_active", True)
            
            new_brand = BrandConfig(
                name=item["name"],
                category=category,
                is_active=is_active
            )
            
            db.add(new_brand)
            db.commit()
            db.refresh(new_brand)
            created.append(new_brand)
            
        except Exception as e:
            errors.append({"item": item, "error": str(e)})
    
    # 刷新配置管理器
    if created:
        config_manager.reload(db)
    
    return {
        "created_count": len(created),
        "error_count": len(errors),
        "errors": errors
    }

@router.put("/brand-config/bulk/status", response_model=Dict[str, Any])
async def bulk_update_brand_status(
    request: BulkStatusUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量更新品牌状态"""
    updated_count = 0
    not_found = []
    
    for brand_id in request.ids:
        db_brand = db.query(BrandConfig).filter(BrandConfig.id == brand_id).first()
        if db_brand:
            db_brand.is_active = request.is_active
            updated_count += 1
        else:
            not_found.append(brand_id)
    
    db.commit()
    
    # 刷新配置管理器
    if updated_count > 0:
        config_manager.reload(db)
    
    return {
        "updated_count": updated_count,
        "not_found": not_found
    }

# 商品名称排除API

@router.get("/product-names", response_model=List[CommonProductNameSchema])
async def get_product_names(
    skip: int = 0, 
    limit: int = 100, 
    category: Optional[str] = None,
    is_active: Optional[bool] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取商品名称排除列表"""
    query = db.query(CommonProductName)
    
    if category:
        query = query.filter(CommonProductName.category == category)
    
    if is_active is not None:
        query = query.filter(CommonProductName.is_active == is_active)
    
    product_names = query.offset(skip).limit(limit).all()
    return product_names

@router.post("/product-names", response_model=CommonProductNameSchema)
async def create_product_name(
    product_name: CommonProductNameCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建商品名称排除项"""
    # 检查是否已存在
    existing = db.query(CommonProductName).filter(CommonProductName.name == product_name.name).first()
    if existing:
        raise HTTPException(status_code=400, detail="商品名称已存在")
    
    new_product_name = CommonProductName(**product_name.dict())
    db.add(new_product_name)
    db.commit()
    db.refresh(new_product_name)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_product_name

@router.put("/product-names/{product_name_id}", response_model=CommonProductNameSchema)
async def update_product_name(
    product_name_id: int,
    product_name: CommonProductNameUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新商品名称排除项"""
    db_product_name = db.query(CommonProductName).filter(CommonProductName.id == product_name_id).first()
    if not db_product_name:
        raise HTTPException(status_code=404, detail="商品名称不存在")
    
    # 如果更新名称，检查新名称是否已存在
    if product_name.name and product_name.name != db_product_name.name:
        existing = db.query(CommonProductName).filter(CommonProductName.name == product_name.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="商品名称已存在")
    
    # 更新字段
    for key, value in product_name.dict(exclude_unset=True).items():
        setattr(db_product_name, key, value)
    
    db.commit()
    db.refresh(db_product_name)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_product_name

@router.delete("/product-names/{product_name_id}")
async def delete_product_name(
    product_name_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除商品名称排除项"""
    db_product_name = db.query(CommonProductName).filter(CommonProductName.id == product_name_id).first()
    if not db_product_name:
        raise HTTPException(status_code=404, detail="商品名称不存在")
    
    db.delete(db_product_name)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "商品名称已删除"}

@router.post("/product-names/bulk", response_model=Dict[str, Any])
async def bulk_create_product_names(
    request: BulkCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建商品名称排除项"""
    created = []
    errors = []
    
    for item in request.items:
        try:
            # 验证必填字段
            if "name" not in item:
                errors.append({"item": item, "error": "缺少必填字段name"})
                continue
            
            # 检查是否已存在
            existing = db.query(CommonProductName).filter(CommonProductName.name == item["name"]).first()
            if existing:
                errors.append({"item": item, "error": "商品名称已存在"})
                continue
            
            # 创建新商品名称
            category = item.get("category")
            description = item.get("description")
            is_active = item.get("is_active", True)
            
            new_product_name = CommonProductName(
                name=item["name"],
                category=category,
                description=description,
                is_active=is_active
            )
            
            db.add(new_product_name)
            db.commit()
            db.refresh(new_product_name)
            created.append(new_product_name)
            
        except Exception as e:
            errors.append({"item": item, "error": str(e)})
    
    # 刷新配置管理器
    if created:
        config_manager.reload(db)
    
    return {
        "created_count": len(created),
        "error_count": len(errors),
        "errors": errors
    }

@router.put("/product-names/bulk/status", response_model=Dict[str, Any])
async def bulk_update_product_name_status(
    request: BulkStatusUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量更新商品名称状态"""
    updated_count = 0
    not_found = []
    
    for product_name_id in request.ids:
        db_product_name = db.query(CommonProductName).filter(CommonProductName.id == product_name_id).first()
        if db_product_name:
            db_product_name.is_active = request.is_active
            updated_count += 1
        else:
            not_found.append(product_name_id)
    
    db.commit()
    
    # 刷新配置管理器
    if updated_count > 0:
        config_manager.reload(db)
    
    return {
        "updated_count": updated_count,
        "not_found": not_found
    }

# 单位配置API

@router.get("/units", response_model=List[UnitConfigSchema])
async def get_units(
    skip: int = 0, 
    limit: int = 100, 
    type: Optional[str] = None,
    is_active: Optional[bool] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取单位列表"""
    query = db.query(UnitConfig)
    
    if type:
        query = query.filter(UnitConfig.type == type)
    
    if is_active is not None:
        query = query.filter(UnitConfig.is_active == is_active)
    
    units = query.offset(skip).limit(limit).all()
    return units

@router.post("/units", response_model=UnitConfigSchema)
async def create_unit(
    unit: UnitConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建单位"""
    # 检查是否已存在
    existing = db.query(UnitConfig).filter(UnitConfig.name == unit.name).first()
    if existing:
        raise HTTPException(status_code=400, detail="单位名称已存在")
    
    new_unit = UnitConfig(**unit.dict())
    db.add(new_unit)
    db.commit()
    db.refresh(new_unit)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_unit

@router.put("/units/{unit_id}", response_model=UnitConfigSchema)
async def update_unit(
    unit_id: int,
    unit: UnitConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新单位"""
    db_unit = db.query(UnitConfig).filter(UnitConfig.id == unit_id).first()
    if not db_unit:
        raise HTTPException(status_code=404, detail="单位不存在")
    
    # 如果更新名称，检查新名称是否已存在
    if unit.name and unit.name != db_unit.name:
        existing = db.query(UnitConfig).filter(UnitConfig.name == unit.name).first()
        if existing:
            raise HTTPException(status_code=400, detail="单位名称已存在")
    
    # 更新字段
    for key, value in unit.dict(exclude_unset=True).items():
        setattr(db_unit, key, value)
    
    db.commit()
    db.refresh(db_unit)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_unit

@router.delete("/units/{unit_id}")
async def delete_unit(
    unit_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除单位"""
    db_unit = db.query(UnitConfig).filter(UnitConfig.id == unit_id).first()
    if not db_unit:
        raise HTTPException(status_code=404, detail="单位不存在")
    
    db.delete(db_unit)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "单位已删除"}

@router.post("/units/bulk", response_model=Dict[str, Any])
async def bulk_create_units(
    request: BulkCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建单位"""
    created = []
    errors = []
    
    for item in request.items:
        try:
            # 验证必填字段
            if "name" not in item:
                errors.append({"item": item, "error": "缺少必填字段name"})
                continue
            
            # 检查是否已存在
            existing = db.query(UnitConfig).filter(UnitConfig.name == item["name"]).first()
            if existing:
                errors.append({"item": item, "error": "单位名称已存在"})
                continue
            
            # 创建新单位
            type = item.get("type")
            is_active = item.get("is_active", True)
            
            new_unit = UnitConfig(
                name=item["name"],
                type=type,
                is_active=is_active
            )
            
            db.add(new_unit)
            db.commit()
            db.refresh(new_unit)
            created.append(new_unit)
            
        except Exception as e:
            errors.append({"item": item, "error": str(e)})
    
    # 刷新配置管理器
    if created:
        config_manager.reload(db)
    
    return {
        "created_count": len(created),
        "error_count": len(errors),
        "errors": errors
    }

# 营销词配置API

@router.get("/marketing-words", response_model=List[MarketingWordConfigSchema])
async def get_marketing_words(
    skip: int = 0, 
    limit: int = 100, 
    category: Optional[str] = None,
    is_active: Optional[bool] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取营销词列表"""
    query = db.query(MarketingWordConfig)
    
    if category:
        query = query.filter(MarketingWordConfig.category == category)
    
    if is_active is not None:
        query = query.filter(MarketingWordConfig.is_active == is_active)
    
    words = query.offset(skip).limit(limit).all()
    return words

@router.post("/marketing-words", response_model=MarketingWordConfigSchema)
async def create_marketing_word(
    word: MarketingWordConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建营销词"""
    # 检查是否已存在
    existing = db.query(MarketingWordConfig).filter(MarketingWordConfig.word == word.word).first()
    if existing:
        raise HTTPException(status_code=400, detail="营销词已存在")
    
    new_word = MarketingWordConfig(**word.dict())
    db.add(new_word)
    db.commit()
    db.refresh(new_word)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_word

@router.put("/marketing-words/{word_id}", response_model=MarketingWordConfigSchema)
async def update_marketing_word(
    word_id: int,
    word: MarketingWordConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新营销词"""
    db_word = db.query(MarketingWordConfig).filter(MarketingWordConfig.id == word_id).first()
    if not db_word:
        raise HTTPException(status_code=404, detail="营销词不存在")
    
    # 如果更新词语，检查新词语是否已存在
    if word.word and word.word != db_word.word:
        existing = db.query(MarketingWordConfig).filter(MarketingWordConfig.word == word.word).first()
        if existing:
            raise HTTPException(status_code=400, detail="营销词已存在")
    
    # 更新字段
    for key, value in word.dict(exclude_unset=True).items():
        setattr(db_word, key, value)
    
    db.commit()
    db.refresh(db_word)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_word

@router.delete("/marketing-words/{word_id}")
async def delete_marketing_word(
    word_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除营销词"""
    db_word = db.query(MarketingWordConfig).filter(MarketingWordConfig.id == word_id).first()
    if not db_word:
        raise HTTPException(status_code=404, detail="营销词不存在")
    
    db.delete(db_word)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "营销词已删除"}

@router.post("/marketing-words/bulk", response_model=Dict[str, Any])
async def bulk_create_marketing_words(
    request: BulkCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """批量创建营销词"""
    created = []
    errors = []
    
    for item in request.items:
        try:
            # 验证必填字段
            if "word" not in item:
                errors.append({"item": item, "error": "缺少必填字段word"})
                continue
            
            # 检查是否已存在
            existing = db.query(MarketingWordConfig).filter(MarketingWordConfig.word == item["word"]).first()
            if existing:
                errors.append({"item": item, "error": "营销词已存在"})
                continue
            
            # 创建新营销词
            category = item.get("category")
            is_active = item.get("is_active", True)
            
            new_word = MarketingWordConfig(
                word=item["word"],
                category=category,
                is_active=is_active
            )
            
            db.add(new_word)
            db.commit()
            db.refresh(new_word)
            created.append(new_word)
            
        except Exception as e:
            errors.append({"item": item, "error": str(e)})
    
    # 刷新配置管理器
    if created:
        config_manager.reload(db)
    
    return {
        "created_count": len(created),
        "error_count": len(errors),
        "errors": errors
    }

# 系统配置API

@router.get("/system", response_model=List[SystemConfigSchema])
async def get_system_configs(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取系统配置列表"""
    configs = db.query(SystemConfig).all()
    return configs

@router.get("/system/{key}", response_model=SystemConfigSchema)
async def get_system_config(
    key: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取特定系统配置"""
    config = db.query(SystemConfig).filter(SystemConfig.key == key).first()
    if not config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    return config

@router.post("/system", response_model=SystemConfigSchema)
async def create_system_config(
    config: SystemConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建系统配置"""
    # 检查是否已存在
    existing = db.query(SystemConfig).filter(SystemConfig.key == config.key).first()
    if existing:
        raise HTTPException(status_code=400, detail="系统配置键名已存在")
    
    new_config = SystemConfig(**config.dict())
    db.add(new_config)
    db.commit()
    db.refresh(new_config)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return new_config

@router.put("/system/{config_id}", response_model=SystemConfigSchema)
async def update_system_config(
    config_id: int,
    config_update: SystemConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新系统配置"""
    db_config = db.query(SystemConfig).filter(SystemConfig.id == config_id).first()
    if not db_config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    
    # 更新字段
    for key, value in config_update.dict(exclude_unset=True).items():
        setattr(db_config, key, value)
    
    db.commit()
    db.refresh(db_config)
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return db_config

@router.delete("/system/{config_id}")
async def delete_system_config(
    config_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除系统配置"""
    db_config = db.query(SystemConfig).filter(SystemConfig.id == config_id).first()
    if not db_config:
        raise HTTPException(status_code=404, detail="系统配置不存在")
    
    db.delete(db_config)
    db.commit()
    
    # 刷新配置管理器
    config_manager.reload(db)
    
    return {"message": "系统配置已删除"}

# 单位与转换规则相关API已迁移到backend/config/routes.py，此处API已废弃
# 为保持向后兼容，保留这些API接口一段时间后再移除 